package com.dmgis.hndz.service.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.IdUtil;
import com.dmgis.hndz.common.utils.SendSMSUtils;
import com.dmgis.hndz.common.utils.StringUtil;
import com.dmgis.hndz.common.utils.SysResult;
import com.dmgis.hndz.mapper.SMSRecordManagementMapper;
import com.dmgis.hndz.mapper.SendUnitManagementMapper;
import com.dmgis.hndz.pojo.SMSRecordManagement;
import com.dmgis.hndz.pojo.SendUnitManagement;
import com.dmgis.hndz.pojoVo.ReceiverVo;
import com.dmgis.hndz.sddz.mapper.Zdda01aMapper;
import com.dmgis.hndz.service.SMSRecordManagementService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author pengdongdong
 * @description public
 * @date 2024-11-05
 */
@Service
public class SMSRecordManagementServiceImpl implements SMSRecordManagementService {

    @Resource
    private SMSRecordManagementMapper sMSRecordManagementMapper;

    @Autowired
    private SendUnitManagementMapper sendUnitManagementMapper;

    @Autowired
    private Zdda01aMapper zdda01aMapper;

    // 市级
    private static final String CITY_UNIT = "自然资源和规划局";
    // 县级
    private static final String COUNTY_UNIT = "自然资源局";

    /**
     * 新增
     *
     * @author pengdongdong
     * @date 2024/11/11
     **/
    public SysResult insertSMSRecordManagement(SMSRecordManagement sMSRecordManagement) {
        // 行政编码
        String code = sMSRecordManagement.getCode();
        // 根据行政编码查询城市名称
        String unitName = sendUnitManagementMapper.selectUnitNameByCode(code);
        // 如果没有行政编码，则新增一个
        if (StringUtil.IsNullOrEmpty(unitName)) {
            String cityName = zdda01aMapper.queryCityName(code);
            if (code.endsWith("0000")) {

            } else if (code.endsWith("00")) {
                // 市级发布单位
                unitName = cityName + CITY_UNIT;
            } else {
                // 县级发布单位
                unitName = cityName + COUNTY_UNIT;
            }
            SendUnitManagement sendUnitManagement = new SendUnitManagement();
            Date date = new Date();
            sendUnitManagement.setId(IdUtil.simpleUUID());
            sendUnitManagement.setCreateTime(date);
            sendUnitManagement.setUpdateTime(date);
            sendUnitManagement.setUnitName(unitName);
            sendUnitManagement.setCode(code);
            sendUnitManagementMapper.insertSendUnitManagement(sendUnitManagement);
        }
        List<ReceiverVo> receiver = sMSRecordManagement.getReceiver();
        if (!CollectionUtils.isEmpty(receiver)) {
            // 需要发送短信的手机号
            String phone = receiver.stream().map(ReceiverVo::getPhone)
                    .collect(Collectors.joining(","));
            // 短信内容
            String content = sMSRecordManagement.getContent() + "【" + unitName + "】";
            int results = SendSMSUtils.sendSMS(phone, content);
            Date date = new Date();
            String stagesId = IdUtil.simpleUUID();
            receiver.forEach(l -> {
                SMSRecordManagement smsRecord = new SMSRecordManagement();
                // 短信是否发送成功，1：成功
                if (results != 1) {
                    // 处理结果（0：发送失败，1：发送成功）
                    smsRecord.setResults("发送失败");
                    smsRecord.setSendStatus("0");
                } else {
                    smsRecord.setResults("发送成功");
                    smsRecord.setSendStatus("1");
                }
                smsRecord.setId(IdUtil.simpleUUID());
                smsRecord.setSendTime(date);
                smsRecord.setRecipient(l.getName());
                smsRecord.setPhone(l.getPhone());
                smsRecord.setDept(l.getDept());
                smsRecord.setDeptId(l.getDeptId());
                smsRecord.setParentId(l.getParentId());
                smsRecord.setPersonId(l.getPersonId());
                smsRecord.setSmsType(sMSRecordManagement.getSmsType());
                smsRecord.setCode(sMSRecordManagement.getCode());
                smsRecord.setSendAisle(sMSRecordManagement.getSendAisle());
                smsRecord.setStaffType(sMSRecordManagement.getStaffType());
                smsRecord.setContent(content);
                smsRecord.setTemplateId(sMSRecordManagement.getTemplateId());
                smsRecord.setSmsCategory(sMSRecordManagement.getSmsCategory());
                smsRecord.setStagesId(stagesId);
                sMSRecordManagementMapper.insertSMSRecordManagement(smsRecord);
            });
            return SysResult.success("发送成功！");
        }
        return SysResult.fail("发送失败！");
    }

    /**
     * 刪除
     *
     * @author pengdongdong
     * @date 2024/11/11
     **/
    public int deleteSMSRecordManagement(String ids) {
        return sMSRecordManagementMapper.deleteSMSRecordManagement(Convert.toStrArray(ids));
    }

    /**
     * 更新
     *
     * @author pengdongdong
     * @date 2024/11/11
     **/
    public int updateSMSRecordManagement(SMSRecordManagement sMSRecordManagement) {
        return sMSRecordManagementMapper.updateSMSRecordManagement(sMSRecordManagement);
    }

    /**
     * 查询 根据主键 id 查询
     *
     * @author pengdongdong
     * @date 2024/11/11
     **/
    public SMSRecordManagement selectSMSRecordManagementById(String id) {
        return sMSRecordManagementMapper.selectSMSRecordManagementById(id);
    }

    /**
     * 查询 分页查询
     *
     * @author pengdongdong
     * @date 2024/11/11
     **/
    public PageInfo<SMSRecordManagement> selectSMSRecordManagementList(Integer pageNum, Integer pageSize, SMSRecordManagement sMSRecordManagement) {
        if (pageNum != null && pageSize != null) {
            PageHelper.startPage(pageNum, pageSize);
        }
        String code = sMSRecordManagement.getCode();
        if (code.endsWith("0000")) {
            // 省级
            sMSRecordManagement.setCode(code.substring(0, 2));
        } else if (code.endsWith("00")) {
            // 市级
            sMSRecordManagement.setCode(code.substring(0, 4));
        } else {
            // 县级
        }
        if (sMSRecordManagement.getSendTime() != null) {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            sMSRecordManagement.setFormatDate(format.format(sMSRecordManagement.getSendTime()));
        }
        return new PageInfo<>(sMSRecordManagementMapper.selectSMSRecordManagementList(sMSRecordManagement));
    }

    public List<SMSRecordManagement> selectSMSRecordManagement(SMSRecordManagement sMSRecordManagement) {
        return sMSRecordManagementMapper.selectSMSRecordManagementList(sMSRecordManagement);
    }

    /**
     * 信息呼叫统计
     *
     * @param dateType  1：本年，2：本月，3：本日 4：本周
     * @param code      行政编码
     * @param startTime 开始时间
     * @param endTime   结束时间
     * @return
     */
    public List<Map<String, Object>> statisticsCallSMS(Integer dateType, String code, String startTime, String endTime) {
        String codeStr = "";
        if (code.endsWith("0000")) {
            // 省级
            codeStr = code.substring(0, 2);
        } else if (code.endsWith("00")) {
            // 市级
            codeStr = code.substring(0, 4);
        } else {
            // 县级
            codeStr = code;
        }
        List<Map<String, Object>> list = new ArrayList<>();
        // 统计短信数
        Map<String, Integer> statisticsSMS = sMSRecordManagementMapper.selectStatisticsSMS(dateType, codeStr, startTime, endTime);
        // 统计短信期数（每发送一次短信算一期）
        Map<String, Integer> statisticsStages = sMSRecordManagementMapper.selectStatisticsStages(dateType, codeStr, startTime, endTime);
        // 统计呼叫人数
        Integer[] selectCallNum = sMSRecordManagementMapper.selectCallNum(dateType, codeStr, startTime, endTime);
        Map<String, Object> redMap = new HashMap<>();
        redMap.put("value", statisticsStages != null && statisticsStages.get("redstages") != null
                ? statisticsStages.get("redstages") : 0);
        redMap.put("smsCount", statisticsSMS != null ? statisticsSMS.get("red") : 0);
        redMap.put("responseCount", selectCallNum != null ? selectCallNum[0] : 0);
        redMap.put("name", "红色预警");
        list.add(redMap);
        Map<String, Object> orangeMap = new HashMap<>();
        orangeMap.put("value", statisticsStages != null && statisticsStages.get("orangestages") != null
                ? statisticsStages.get("orangestages") : 0);
        orangeMap.put("smsCount", statisticsSMS != null ? statisticsSMS.get("orange") : 0);
        orangeMap.put("responseCount", selectCallNum != null ? selectCallNum[1] : 0);
        orangeMap.put("name", "橙色预警");
        list.add(orangeMap);
        Map<String, Object> yellowMap = new HashMap<>();
        yellowMap.put("value", statisticsStages != null && statisticsStages.get("yellowstages") != null
                ? statisticsStages.get("yellowstages") : 0);
        yellowMap.put("smsCount", statisticsSMS != null ? statisticsSMS.get("yellow") : 0);
        yellowMap.put("responseCount", selectCallNum != null ? selectCallNum[2] : 0);
        yellowMap.put("name", "黄色预警");
        list.add(yellowMap);
        return list;
    }


    /**
     * 统计市县级呼叫人数
     *
     * @param code      行政编码
     * @param startTime 开始时间
     * @param endTime   结束时间
     * @return
     */
    public List<Map<String, String>> selectCallNum(String code, String startTime, String endTime) {
        List<Map<String, String>> list = new ArrayList<>();
        if (code.endsWith("0000")) {
            // 省级
            list = sMSRecordManagementMapper.selectCallNumCity(startTime, endTime);
        } else if (code.endsWith("00")) {
            // 市级
            list = sMSRecordManagementMapper.selectCallNumCounty(code, startTime, endTime);
        } else {
            // 县级
            list = sMSRecordManagementMapper.selectCallNumCountyByCode(code, startTime, endTime);
        }
        return list;
    }

}